import { fileURLToPath, URL } from 'node:url'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vueJsx from '@vitejs/plugin-vue-jsx'
import postCssPxToRem from 'postcss-pxtorem'
import vue from '@vitejs/plugin-vue'
import libCss from 'vite-plugin-libcss'
import viteCompression from 'vite-plugin-compression'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { terser } from 'rollup-plugin-terser'; // 压缩js
// https://vitejs.dev/config/
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
  return {
    transpileDependencies: true,
    plugins: [
      vue(),
      vueJsx(),
      libCss(),
      terser({
        output: {
          comments: false, // 移除注释
        },
        compress: {
          passes: 2, // 多次遍历代码进行压缩
          pure_funcs: ['console.log', 'debugger'], // 压缩时移除console.log
        },
      }),
    ],
    server: {
      //本地服务器主机名 配置后可以使用本地网络访问
      host: true,
      //指定启动端口号
      port: 5180,
      //设为 true 时若端口已被占用则会直接退出，而不是尝试下一个可用端口
      strictPort: false,
      //服务器启动时自动在浏览器中打开应用程序,当此值为字符串时，会被用作 URL 的路径名
      open: true,
      proxy: {
          '/auditPortal': {
              target: 'http://127.0.0.1:3000',
              // target: 'http://192.168.108.62:8099/auditPortal',
              changeOrigin: true,
              // rewrite: (path) => path.replace(/^\/auditPortal/, ''),
              rewrite: (path) => path.replace(/^\/auditPortal/, '/proxy/auditPortal/?api=/auditPortal')
            },
          /* '/upload': {
              target: 'http://127.0.0.1:8083/html/',
              changeOrigin: true,
              // rewrite: (path) => path.replace(/^\/file/, ''),
          } */
        }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        'vue': 'vue/dist/vue.esm-bundler.js',
      }
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            // 自适应，px>rem转换
            rootValue: 192.0,
            propList: ["*", "!border"], // 除 border 外所有px 转 rem
            selectorBlackList: [""] // 过滤掉.el-开头的class，不进行rem转换
          }),
        ],
      },
    },
    build: {
      lib: {
        entry: resolve(__dirname, './src/lib_main.js'),
        name: 'vPageCRUD',
        formats: ['es'],
        esbuild: {
          drop: ["console", "debugger"],
        }
      },
      rollupOptions: {
        // 确保外部化处理那些你不想打包进库的依赖
        external: ['vue', 'element-plus'],
        output: {
       // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
          globals: {
            vue: 'Vue',
            'element-plus': 'ElementPlus'
          },
        },
      }
    }
  }
})
